package com.heima.wemedia.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.admin.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Value("${file.oss.prefix}")
    private String prefix;

    @Value("${file.oss.web-site}")
    private String webSite;
//上传
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1. 校验上传的文件类型
        if(multipartFile==null || multipartFile.getSize()==0){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请上传正确的文件");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请登录后操作");
        }
        String filename = multipartFile.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        if(!checkFileSuffix(suffix)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请上传正确的素材格式,[jpg,jpeg,png,gif]");
        }
        //2. 上传到oss
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        try {
            //文件上传成功
            String store = fileStorageService.store(prefix, fileName + suffix, multipartFile.getInputStream());//上传目录，文件名称，输入流
            //素材表添加数据
            WmMaterial wmMaterial = new WmMaterial();

            wmMaterial.setUserId(user.getId());
            wmMaterial.setUrl(store);
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short)0);
            wmMaterial.setCreatedTime(new Date());
            save(wmMaterial);
            return ResponseResult.okResult();
        } catch (IOException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"文件上传失败，服务器异常" );
        }
        return null;
    }
//查看列表
    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        //1.校验参数
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.执行查询
        // 2.1 分页查询
        Page<WmMaterial> pageReq = new Page<>(dto.getPage(), dto.getSize());
        //2.2参数查询
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.<WmMaterial>lambdaQuery();

        //收藏字段不为空 按收藏查询
        if(WemediaConstants.COLLECT_MATERIAL.equals(dto.getIsCollection()) ){
            queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //按用户查询
        queryWrapper.eq(WmMaterial::getUserId,user.getId());
        //按时间降序
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> pageResult = page(pageReq, queryWrapper);
        //3.封装
        List<WmMaterial> records = pageResult.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite+record.getUrl());
        }
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal(),records);
        return result;
    }


    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
//删除
    @Override
    public ResponseResult delPicture(Integer id) {
        //1.参数校验
        if(id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.业务处理
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断是否在引用
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = Wrappers.<WmNewsMaterial>lambdaQuery();
        queryWrapper.eq(WmNewsMaterial::getNewsId, id);
        int count =wmNewsMaterialMapper.selectCount(queryWrapper);
        if (count>0){
            CustException.cust( AppHttpCodeEnum.DATA_NOT_ALLOW,"图片已被引用");
        }
        //删除库
        removeById(id);
        //删除图片oss
        fileStorageService.delete(wmMaterial.getUrl());
        //封装结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 检查文件格式 目前仅仅支持jpg  jpeg  png  gif 图片的上传
     * @param path
     * @return
     */
    private boolean checkFileSuffix(String path){
        if(StringUtils.isBlank(path)) return false;
        List<String> allowSuffix = Arrays.asList("jpg", "jpeg", "png", "gif");
        boolean isAllow = false;
        for (String suffix : allowSuffix) {
            if(path.endsWith(suffix)){
                isAllow = true;
                break;
            }
        }
        return isAllow;
    }


    //收藏
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数
        if(id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.更新状态
        WmMaterial material = getById(id);
        if (material == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材信息不存在");
        }
        //获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        if(!material.getUserId().equals(uid)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"只允许收藏自己上传的素材");
        }
        material.setIsCollection(type);
        updateById(material);
//        update(Wrappers.<WmMaterial>lambdaUpdate()  // 如果只想修改指定字段 可以使用此方法
//                .set(WmMaterial::getIsCollection,type)
//                .eq(WmMaterial::getId,id)
//                .eq(WmMaterial::getUserId,uid));
        return ResponseResult.okResult();
    }
}
